﻿using System;
using System.Linq;
using Pro.Common;
using Pro.Common.IoC;

namespace Pro
{
    public class EngineContext
    {
        private static readonly object locker = new object();
        private static IEngine _engine { get; set; }

        public static IEngine Current
        {
            get
            {
                //Singleton
                if (null == _engine)
                {
                    lock (locker)
                    {
                        if (null == _engine)
                        {
                            _engine = CreateEngineInstance();
                        }
                    }
                }
                return _engine;
            }
        }

        public static IEngine CreateEngineInstance()
        {
            var typeFinder = new WebAppTypeFinder();
            Type[] engines = typeFinder.FindClassesOfType(typeof (IEngine), typeFinder.GetAssemblies()).ToArray();
            if (engines.Any())
            {
                var defaultEngine = (IEngine) Activator.CreateInstance(engines[0]);
                return defaultEngine;
            }
            throw new ApplicationException("Can not find any IoC engines in the context. ");
        }
    }
}